package top.yrlby.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author BaiYang
 * @time 2022/9/5
 */
@Slf4j
//捕获@Controller下的方法
@RestControllerAdvice //简写 == @ControllerAdvice + @ResponseBody
public class GlobalExceptionHandler {
    //捕获异常方法
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)//
    //方法名随意,参数写捕获的异常
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        //ex.getMessage()获取异常中的输出语句
        //.contains获取异常中的是否包含"Duplicate entry"
        if(ex.getMessage().contains("Duplicate entry")){
            String[] s=ex.getMessage().split(" ");//以空格切割异常中的输出语句
            String msg=s[2]+"该账号已存在!";//拼接输出字符串
            return R.error(msg);
        }
        return R.error("请重试！");//如果不是包含"Duplicate entry"的异常，则跳过if输出这句话
    }

    /**
     * 捕获自定义异常
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());

        //返回自定义异常设置的输出语句
        return R.error(ex.getMessage());
    }
}
